package com.lanlian.cayman.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.bean.ReqIsTrade;
import com.lanlian.commonlib.bean.ReqPositionDetails;
import com.lanlian.commonlib.bean.RespPositionDetails;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.data.RespIsTrade;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.LoginActivity;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.utillib.DisplayUtil;
import com.oms.rpc.protobuf.FuturesTradeInfo;
import com.oms.rpc.protobuf.FuturesTradeResp;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * 下单对话框
 */
public class MakeOrderDialog extends Dialog implements View.OnClickListener {

    private BaseActivity mActivity;

    private ViewPager mViewPager;
    private MagicIndicator mMagicIndicator;
    private TextView mTvContractName;
    private TextView mTvPositionNum;
    private ImageView mImgReduce;
    private EditText mEtNum;
    private ImageView mImgPlus;
    private TextView mTvMoney;
    private ImageView mImgReduce2;
    private EditText mEtPrice;
    private ImageView mImgPlus2;
    private TextView mTvBuy;
    private TextView mTvSell;
    private TextView mTvPing;
    private TradeConfirmDialog mTradeConfirmDialog;

    private String[] mTitleList = new String[]{"市价下单", "限价下单"};
    private ArrayList<PositionDetailsInfo> mList = new ArrayList<>();

    private RespIsTrade mRespIsTrade;
    private PositionDetailsInfo mPositionDetailsInfo;
    private String mContractCode;
    private String mContractName;
    private String mCurrencyPrice;
    private int mStatus;
    private String scale;

    private String mNum;
    private String mPrice;
    private int mOrderType;
    private int mPriceType = 1;

    public MakeOrderDialog(Context context) {
        super(context, R.style.customDialog);
        this.mActivity = (BaseActivity) context;
    }

    public MakeOrderDialog(Context context, PositionDetailsInfo positionDetailsInfo) {
        super(context, R.style.customDialog);
        this.mActivity = (BaseActivity) context;
        this.mPositionDetailsInfo = positionDetailsInfo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_make_order);
        ViewGroup.LayoutParams params = getWindow().getAttributes();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        initView();
        setListener();
        initNavigator();
        if (mPositionDetailsInfo == null) {
            getPositionDetails();
        } else {
            setPosition(mPositionDetailsInfo);
        }
        changeView();
        mTvContractName.setText(mContractCode);
        mTvMoney.setText(String.format("%.2f", LLApplication.getAvailableFunds()));
        if (mContractCode != null) {
            scale = MarketFragment.getRespMarket().getGoods(mContractCode).minChange;
        }
        if (mStatus == 1) {
            mTvBuy.setBackgroundResource(R.drawable.bg_kline_order3);
            mTvSell.setBackgroundResource(R.drawable.bg_kline_order2);
        } else if (mStatus == 2) {
            mTvBuy.setBackgroundResource(R.drawable.bg_kline_order2);
            mTvSell.setBackgroundResource(R.drawable.bg_kline_order3);
        } else {
            mTvBuy.setBackgroundResource(R.drawable.bg_kline_order2);
            mTvSell.setBackgroundResource(R.drawable.bg_kline_order2);
        }
    }

    public void initData(String contractCode, String contractName, String price) {
        this.mContractCode = contractCode;
        this.mContractName = contractName;
        this.mCurrencyPrice = price;
    }

    private void initView() {
        mViewPager = findViewById(R.id.view_pager);
        mMagicIndicator = findViewById(R.id.magic_indicator);
        mTvContractName = findViewById(R.id.tv_contract_name);
        mTvPositionNum = findViewById(R.id.tv_position_num);
        mImgReduce = findViewById(R.id.img_reduce);
        mEtNum = findViewById(R.id.et_num);
        mImgPlus = findViewById(R.id.img_plus);
        mTvMoney = findViewById(R.id.tv_money);
        mImgReduce2 = findViewById(R.id.img_reduce2);
        mEtPrice = findViewById(R.id.et_price);
        mImgPlus2 = findViewById(R.id.img_plus2);
        mTvBuy = findViewById(R.id.tv_buy);
        mTvSell = findViewById(R.id.tv_sell);
        mTvPing = findViewById(R.id.tv_ping);
    }

    private void setListener() {
        mImgPlus.setOnClickListener(this);
        mImgReduce.setOnClickListener(this);
        mImgPlus2.setOnClickListener(this);
        mImgReduce2.setOnClickListener(this);
        mTvBuy.setOnClickListener(this);
        mTvSell.setOnClickListener(this);
        mTvPing.setOnClickListener(this);
        mEtPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mPriceType == 2) {
                    mCurrencyPrice = s.toString();
                }
            }
        });
    }

    /**
     * 0市价 1限价
     */
    private void changeView() {
        if (mPriceType == 1) {
            mEtPrice.setText("市价");
            mEtPrice.setEnabled(false);
            mImgReduce2.setVisibility(View.INVISIBLE);
            mImgPlus2.setVisibility(View.INVISIBLE);
        } else {
            mEtPrice.setEnabled(true);
            if (!TextUtils.isEmpty(mCurrencyPrice)) {
                mEtPrice.setText(mCurrencyPrice);
            } else {
                mEtPrice.setText("0");
            }
            mImgReduce2.setVisibility(View.VISIBLE);
            mImgPlus2.setVisibility(View.VISIBLE);
        }
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(mActivity);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(0xffa1adc8);
                colorTransitionPagerTitleView.setSelectedColor(0xff6385cf);
                colorTransitionPagerTitleView.setText(mTitleList[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                        switch (index) {
                            case 0:
                                mPriceType = 1;
                                break;
                            case 1:
                                mPriceType = 2;
                                break;
                            default:
                                break;
                        }
                        changeView();
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
                indicator.setRoundRadius(DisplayUtil.dip2px(context, 1));
                indicator.setLineHeight(DisplayUtil.dip2px(context, 2));
                indicator.setColors(0xff6385cf);
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setAdapter(new FragmentPagerAdapter(mActivity.getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return new BaseFragment();
            }

            @Override
            public int getCount() {
                return mTitleList.length;
            }
        });
    }

    /**
     * 平仓状态 1 当前有多仓 买置灰  2当前有空仓 卖置灰
     * 其他状态不管
     */
    public void setStatus(int status) {
        this.mStatus = status;
    }

    private void setPosition(PositionDetailsInfo positionDetailsInfo) {
        this.mPositionDetailsInfo = positionDetailsInfo;
        if (!TextUtils.isEmpty(positionDetailsInfo.getcPositionFlag())) {
            if ("1".equals(positionDetailsInfo.getcPositionFlag())) {
                mTvPositionNum.setText(String.format("多 %d 手", positionDetailsInfo.getlCurrentAmount()));
            } else {
                mTvPositionNum.setText(String.format("空 %d 手", positionDetailsInfo.getlCurrentAmount()));
            }
        }
    }

    @Override
    public void onClick(View view) {
        StringBuilder stringBuilder = new StringBuilder();
        switch (view.getId()) {
            case R.id.tv_buy:
                if (!mActivity.mDBManager.isLogined()) {
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(intent);
                    return;
                }
                if (!checkData()) {
                    return;
                }
                stringBuilder.append(mContractName);
                stringBuilder.append("，价格：");
                if ("0".equals(mPrice)) {
                    stringBuilder.append("市价");
                } else {
                    stringBuilder.append(mPrice);
                }
                stringBuilder.append("，买：");
                stringBuilder.append(mNum);
                stringBuilder.append("手");
                mOrderType = 1;
                if (DBManager.getInstance().getSecondConfirm()) {
                    mTradeConfirmDialog = new TradeConfirmDialog(mActivity);
                    mTradeConfirmDialog.setText(stringBuilder.toString());
                    mTradeConfirmDialog.setOnOk(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            isTrade();
                        }
                    });
                    mTradeConfirmDialog.showDialog();
                } else {
                    isTrade();
                }
                break;
            case R.id.tv_sell:
                if (!mActivity.mDBManager.isLogined()) {
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(intent);
                    return;
                }
                if (!checkData()) {
                    return;
                }
                stringBuilder.append(mContractName);
                stringBuilder.append("，价格：");
                if ("0".equals(mPrice)) {
                    stringBuilder.append("市价");
                } else {
                    stringBuilder.append(mPrice);
                }
                stringBuilder.append("，卖：");
                stringBuilder.append(mNum);
                stringBuilder.append("手");
                mOrderType = 2;
                if (DBManager.getInstance().getSecondConfirm()) {
                    mTradeConfirmDialog = new TradeConfirmDialog(mActivity);
                    mTradeConfirmDialog.setText(stringBuilder.toString());
                    mTradeConfirmDialog.setOnOk(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            isTrade();
                        }
                    });
                    mTradeConfirmDialog.showDialog();
                } else {
                    isTrade();
                }
                break;
            case R.id.img_reduce:
                if (Integer.valueOf(mEtNum.getText().toString()) > 1) {
                    mEtNum.setText(String.valueOf(Integer.valueOf(mEtNum.getText().toString()) - 1));
                }
                break;
            case R.id.img_reduce2:
                if ((Double.valueOf(mEtPrice.getText().toString()) > Double.parseDouble(scale))) {
                    mCurrencyPrice = new BigDecimal(mEtPrice.getText().toString()).subtract(new BigDecimal(scale)).toPlainString();
                    mEtPrice.setText(mCurrencyPrice);
                }
                break;
            case R.id.img_plus:
                mEtNum.setText(String.valueOf(Integer.valueOf(mEtNum.getText().toString()) + 1));
                break;
            case R.id.img_plus2:
                mCurrencyPrice = new BigDecimal(mEtPrice.getText().toString()).add(new BigDecimal(scale)).toPlainString();
                mEtPrice.setText(mCurrencyPrice);
                break;
            default:
                break;
        }
    }

    /**
     * 检查数据
     */
    private boolean checkData() {
        mNum = mEtNum.getText().toString();
        if (mPriceType == 1) {
            mPrice = "0";
        } else {
            mPrice = mEtPrice.getText().toString();
        }
        if (TextUtils.isEmpty(mNum) || "0".equals(mNum)) {
            mActivity.showToast("请输入数量");
            return false;
        }
        if (!TextUtils.isEmpty(mPrice)) {
            if (mPriceType == 2 && "0".equals(mPrice)) {
                mActivity.showToast("价格不能为零");
                return false;
            }
        }
        return true;
    }

    /**
     * 下单
     */
    private void markOrder() {
        try {
            ProtoManager pm = new ProtoManager();
            FuturesTradeInfo.Builder fb = pm.getFuturesTradeInfoBuilder();
            fb.setVcFuturesCode(mContractCode);
            fb.setLOrderAmount(Long.parseLong(mNum));
            fb.setEnOrderPrice(Double.parseDouble(mPrice));
            fb.setCPriceType(String.valueOf(mPriceType));
            fb.setCOrderDirection(String.valueOf(mOrderType));
            fb.setLPositionNo(mPositionDetailsInfo.getlPositionNo().intValue());
            //下面的方法必须最后调用
            OMSTradeReq.Builder oms = pm.getRequst(1);
            OMSTradeReq om = oms.build();
            SocketCallImpl sc = new SocketCallImpl(mActivity) {
                @Override
                public void message(byte[] data) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (byte aData : data) {
                        stringBuilder.append(aData).append(" ");
                    }
                    Log.e("下单", stringBuilder.toString());
                    try {
                        OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                        if (oms.getRequestStatus() == 0) {
                            FuturesTradeResp fr = oms.getFuturestradeResp();
                            if (fr.getErrcode() == 0) {
                                mActivity.showToast("下单成功");
                                mTradeConfirmDialog.dismiss();
                                dismiss();
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                            } else {
                                mActivity.showToast(fr.getErrmsg());
                            }
                        } else {
                            mActivity.showToast(oms.getRequestStatus() + ":" + oms.getStatusInfo());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            MySocketManager ms = new MySocketManager();
            ms.sendData(om.toByteArray(), sc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否可以交易
     */
    private void isTrade() {
        ReqIsTrade reqIsTrade = new ReqIsTrade();
        if (MarketFragment.getRespMarket() == null) {
            return;
        }
        reqIsTrade.setGoodsNo(MarketFragment.getRespMarket().getGoods(mContractCode).goodsNo);
        reqIsTrade.setContractNo(mContractCode);
        reqIsTrade.setType(String.valueOf(mOrderType));
        VolleyRequestUtils.getInstance().sendRequest(this.toString(), reqIsTrade, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                mActivity.dismissLoadingDialog();
                mRespIsTrade = (RespIsTrade) response;
                if (mRespIsTrade != null) {
                    if (mRespIsTrade.getFlag()) {
                        markOrder();
                    } else {
                        mActivity.showToast(mRespIsTrade.getMsg());
                    }
                }
            }

            @Override
            public void onFail(BaseResponse response) {
                mActivity.showToast(response.getMsg());
            }
        });
    }

    /**
     * 获取持仓信息
     */
    private void getPositionDetails() {
        VolleyRequestUtils.getInstance().getPositionDetails(this.toString(), new ReqPositionDetails(),
                new INetWorkCallback() {
                    @Override
                    public void onSuccess(Object response) {
                        RespPositionDetails respPositionDetails = (RespPositionDetails) response;
                        mList = respPositionDetails.getDataList();
                        if (mList != null) {
                            for (PositionDetailsInfo positionDetailsInfo : mList) {
                                if (positionDetailsInfo.getVcContractCode().equals(mContractCode)) {
                                    setPosition(positionDetailsInfo);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFail(BaseResponse baseResponse) {
                        mActivity.showToast(baseResponse.getMsg());
                    }
                });
    }

    public void showDialog() {
        Window w = getWindow();
        w.setWindowAnimations(com.lanlian.uikit.R.style.animFromBottom);
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.gravity = Gravity.BOTTOM;
        onWindowAttributesChanged(lp);
        setCanceledOnTouchOutside(true);
        show();
    }

}